package com.zenika.zenbinding.client.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.ui.Widget;
import com.zenika.zenbinding.client.exception.DataMessage;
import com.zenika.zenbinding.client.feedback.DummyFeedbackManager;
import com.zenika.zenbinding.client.handler.Handler;
import com.zenika.zenbinding.client.renderer.Renderer;

public class CellModel {

	private List listenerList;
	private Renderer renderer;
	private BusinessObject object;
	private Handler tableHandler;
	private int row;
	private int column;

	public CellModel(int row, int column, BusinessObject object, Renderer renderer) {
		this.listenerList = new ArrayList();
		this.row = row;
		this.object = object;
		this.column = column;
		this.renderer = renderer;
	}

	/**
	 * We request an handler in parameter to identify which handler had
	 * requested the view.
	 * @param handler
	 * @return The widget to display in the cell
	 */
	public Widget getView(Handler handler) {
		this.tableHandler = handler;
		DummyFeedbackManager dummy = new DummyFeedbackManager(this);
		return this.renderer.render(this.object, dummy);
	}

	public void fireError(DataMessage message) {
		Iterator iter = this.listenerList.iterator();
		while (iter.hasNext()) {
			((CellModelListener) iter.next()).onEnteringErrorState(this.row, this.column, this.tableHandler, message);
		}
	}

	public void fireErrorStop() {
		Iterator iter = this.listenerList.iterator();
		while (iter.hasNext()) {
			((CellModelListener) iter.next()).onLeavingErrorState(this.row, this.column, this.tableHandler);
		}
	}

	public void addCellModelListener(CellModelListener listener) {
		this.listenerList.add(listener);
	}

	public void removeCellModelListener(CellModelListener listener) {
		this.listenerList.remove(listener);
	}
}
